package User

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"encoding/json"
	"github.com/mojocn/base64Captcha"
	"log"
	"time"
)

type RegisterController struct {
	controllers.MainController
}

//ConfigJsonBody json request body.
type RegisterBody struct {
	//用户登录信息
	AccountName string //用户名
	Password    string //密码
	Sex         string //性别
	Email       string //邮箱
	Birthday    string //出生日期
	Address     string //住址

	//验证码信息
	Id          string
	VerifyValue string
}

//处理注册表单
func (this *RegisterController) RegisterPost() {
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	var postParameters RegisterBody
	err1 := decoder.Decode(&postParameters)
	if err1 != nil {
		body := map[string]interface{}{"code": 300, "data": "验证失败", "msg": "提交表单信息不全"}
		this.Data["json"] = body
		this.ServeJSON()
		log.Fatal(err1)
		return
	}
	//检测表单信息有效
	if postParameters.AccountName == "" || postParameters.Password == "" || postParameters.Sex == "" || postParameters.Email == "" || postParameters.Birthday == "" || postParameters.VerifyValue == "" {
		body := map[string]interface{}{"code": 301, "data": "验证失败", "msg": "提交表单信息异常"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}

	//verify the captcha
	//比较图像验证码
	verifyResult := base64Captcha.VerifyCaptcha(postParameters.Id, postParameters.VerifyValue)

	//set json response
	if verifyResult {
		//插入用户数据
		db := models.ConnDb()
		defer db.Close()
		birthday, err2 := time.Parse("2006-01-02", postParameters.Birthday)
		if err2 != nil {
			body := map[string]interface{}{"code": 303, "data": "验证失败", "msg": "服务器异常"}
			this.Data["json"] = body
			this.ServeJSON()
			log.Fatal(err2)
			return
		}

		user := User.TbUser{Username: postParameters.AccountName, Password: postParameters.Password, Sex: postParameters.Sex, Email: postParameters.Email, Birthday: birthday, Address: postParameters.Address}
		err3 := db.Create(&user).Error //插入操作
		if err3 != nil {
			body := map[string]interface{}{"code": 303, "data": "验证失败", "msg": "服务器异常"}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
		body := map[string]interface{}{"code": 200, "data": "注册成功", "msg": "注册成功"}
		this.Data["json"] = body
		this.ServeJSON()
		return

	} else {
		body := map[string]interface{}{"code": 302, "data": "验证失败", "msg": "验证码无效"}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
}
